//
//  MZCollBackgroundFlowLayout.swift
//  MZTool
//
//  Created by gby on 2023/3/2.
//

import Foundation
import UIKit

public protocol MZFlowLayout_BackgroundDelegate: NSObject {
    
    func collbacklayout(_ collectionView: UICollectionView?, layout collectionViewLayout: MZFlowLayout_Background, insertForSectionAtIndex section: Int) -> UIEdgeInsets
    
    func collbackDecorationViewKind(insertForSectionAtIndex section: Int) -> String?
    
}



@MainActor open class MZFlowLayout_Background: UICollectionViewFlowLayout {
    
    private lazy var layoutInfoList:[UICollectionViewLayoutAttributes] = []
    private lazy var contentSize: CGSize = CGSize.zero
    public weak var backDelegate: MZFlowLayout_BackgroundDelegate?
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override init() {
        super.init()
    }
    
    public override func prepare() {
        super.prepare()
        
        self.layoutInfoList.removeAll()
        let numberOfSections = self.collectionView?.numberOfSections ?? 0
        
        for section in 0..<numberOfSections {
            
            let num = self.collectionView?.numberOfItems(inSection: section) ?? 0
            var first: UICollectionViewLayoutAttributes?
            var last: UICollectionViewLayoutAttributes?
            if num > 0{
                first = self.layoutAttributesForItem(at: IndexPath.init(row: 0, section: section))
                last = self.layoutAttributesForItem(at: IndexPath.init(row: num - 1, section: section))
            }
            
            var sectionInset = self.sectionInset
            let collViewInst: UIEdgeInsets = self.collectionView?.contentInset ?? UIEdgeInsets.zero
            //FIX:
            let inset = self.backDelegate?.collbacklayout(self.collectionView, layout: self, insertForSectionAtIndex: section) ?? UIEdgeInsets.zero
            
            if inset != UIEdgeInsets.zero {
                sectionInset = inset
            }
            
            let headerSize = CGSize.zero
            let footerSize = CGSize.zero
            
            var sectionFrame = CGRect.zero
            let firstFrame = first?.frame ?? CGRect.zero
            let lastFrame = last?.frame ?? CGRect.zero
            if self.scrollDirection == .horizontal {
                sectionFrame = CGRect.init(x: firstFrame.minX - headerSize.width + sectionInset.left,
                                           y: firstFrame.minY + sectionInset.top,
                                           width: lastFrame.maxX - sectionInset.right,
                                           height: lastFrame.maxY - sectionInset.bottom)
                sectionFrame.origin.y = sectionInset.top
                sectionFrame.size.width = sectionFrame.size.width - sectionFrame.origin.x
                sectionFrame.size.height = (self.collectionView?.frame.height ?? 0) - sectionInset.top - sectionInset.bottom
                
            }else {
                let x = firstFrame.minX - sectionInset.left
                let y = firstFrame.minY - headerSize.height - sectionInset.top
                var with = lastFrame.maxX + sectionInset.left + sectionInset.right - collViewInst.left
                if let colwidth = self.collectionView?.frame.width {
                    with = colwidth - collViewInst.left - collViewInst.right - self.sectionInset.left - self.sectionInset.right + sectionInset.left + sectionInset.right
                }
                sectionFrame = CGRect.init(x: x,
                                           y: y,
                                           width: with,
                                           height: lastFrame.maxY - y + sectionInset.bottom + footerSize.height)
            }
            
            if let decorationKind = self.backDelegate?.collbackDecorationViewKind(insertForSectionAtIndex: section) {
                let att = self.layoutAttributesForDecorationView(ofKind: decorationKind, at: IndexPath.init(row: 0, section: section))
                att?.frame = sectionFrame
                att?.zIndex = -1
                att?.isHidden = (self.collectionView?.numberOfItems(inSection: section) == 0) ? true : false
                if let attt = att {
                    self.layoutInfoList.append(attt)
                }
            }
        }
    }
    
    public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let arr: [UICollectionViewLayoutAttributes]? = super.layoutAttributesForElements(in: rect)
        var rt: [UICollectionViewLayoutAttributes] = []
        rt.append(contentsOf: arr ?? [])
        for (_, att) in self.layoutInfoList.enumerated() {
            if CGRectIntersectsRect(att.frame, rect) {
                rt.append(att)
            }
        }
        return rt
    }
    
    public override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attrs = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, with: indexPath)
        return attrs
    }
}
